package com.zy.fee.roadpark.activity.nb;

import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.shouzhong.scanner.ScannerUtils;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.FileLogic;
import com.zy.fee.roadpark.dao.NbNodeRecordLogic;
import com.zy.fee.roadpark.model.M_Node;
import com.zy.fee.roadpark.model.M_NodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordInfo;
import com.zy.fee.roadpark.util.Printer;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.FileUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.util.ArrayList;

/**
 * Created by Wikison on 2019/3/28. 登记车牌
 */
public class NbRegistrationPlateActivity extends BaseActivity {
  public static final String INTENT_IS_FORENSIC = "INTENT_IS_FORENSIC";
  public static final String INTENT_ORIGIN_PLATE = "INTENT_ORIGIN_PLATE";

  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.tv_time) TextView tvTime;
  @BindView(R.id.view) View view;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;

  private ArrayList<ImageItem> images = null;
  private M_Node mNode;
  private String code, plateNumber;
  private boolean isReForensics;
  private String originPlateNumber = "";
  private M_NodeRecord nodeRecord;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_nb_registration_plate);
  }

  @Override public void init() {
    registerReceiver(new String[] { Constants.BROADCAST_REFRESH_NODE_LIST });

    initData();
    initView();
    initListener();
  }

  private void initData() {
    initImagePickerSingle(false);

    mNode = (M_Node) getIntent().getSerializableExtra(NbSpotListActivity.INTENT_NODE);
    isReForensics = getIntent().getBooleanExtra(INTENT_IS_FORENSIC, false);
    originPlateNumber = getIntent().getStringExtra(INTENT_ORIGIN_PLATE);
  }

  private void initView() {
    lhTvTitle.setText("登记车牌");

    if (mNode != null) {
      code = mNode.getCode();
      etCode.setText(code);
      etCode.setEnabled(false);
      plateNumber = mNode.getCarNumber();
      gpvPlateNumber.setPassword(plateNumber);

      tvTime.setText(mNode.getShowState() == 0 ? "00:00:00"
          : DateTimeUtil.getSecondsFormat(mNode.getSeconds()));
    } else {
      mNode = new M_Node();
    }
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        if (position == 0) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.provice));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 1 && position < 2) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.english));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 2 && position <= 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty_without_chinese));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        }
        viewKeyboard.setVisibility(View.GONE);
        return false;
      }

      @Override public void onTextChanged(String psw) {
      }

      @Override public void onInputFinish(String psw) {
      }
    });

    etCode.setOnFocusChangeListener((view, hasFocus) -> {
      if (hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      } else {
        InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
      }
    });

    view.setOnClickListener(v -> viewKeyboard.setVisibility(View.GONE));

    gpvPlateNumber.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      }
    });
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    super.handleReceiver(context, intent);
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_REFRESH_NODE_LIST.equals(intent.getAction())) {
      finish();
    }
  }

  private void printTicket() {
    try {
      Printer.printT(plateNumber, (StringUtils.isBlank(mNode.getStartTime()) ? DateTimeUtil.getCurrentTime()
        : mNode.getStartTime()), Constants.PAY_NB_URL + nodeRecord.getNodeRecordID(), false, preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID));
      Intent intent = new Intent(mContext, NbForensicsActivity.class);
      intent.putExtra(NbSpotListActivity.INTENT_NODE, mNode);
      intent.putExtra(INTENT_IS_FORENSIC, isReForensics);
      intent.putExtra(INTENT_ORIGIN_PLATE, originPlateNumber);
      startActivity(intent);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
//        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//        String path = images.get(0).path;
//        String plate = "";
//        try {
//          plate = ScannerUtils.decodeLicensePlate(mContext,
//              ImageUtil.createImageThumbnail(path, 200 * 1024));
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
//        if (StringUtils.isBlank(plate)) {
//          ocr_vehicle_plate(path);
//        } else {
//          ToastUtil.showMessage(mContext, "识别成功。");
//          gpvPlateNumber.setPassword(plate);
//          FileUtil.deleteSingleFile(path);
//          FileUtil.deletePicture(mContext, path);
//        }

        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        String path = images.get(0).path;
        ocr_vehicle_plate(path);
      }
    }
  }

  /**
   * 车牌识别
   */
  private void ocr_vehicle_plate(String path) {

    FileLogic.GetCPSB(mContext, path, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        String plateNum = (String) obj;
        if (!StringUtils.isBlank(plateNum) && (plateNum.length() == 7 || plateNum.length() == 8)) {
          gpvPlateNumber.setPassword(plateNum);

          FileUtil.deleteSingleFile(path);
          FileUtil.deletePicture(mContext, path);
        } else {
          ToastUtil.showMessage(mContext, "识别出的车牌号有误");
        }
      }

      @Override public void onFailed() {
        ToastUtil.showMessage(mContext, "识别失败，请重新识别或手动输入");
      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @OnClick({
      R.id.ll_back,R.id.iv_scan, R.id.tv_button
  }) public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_scan:
        picOne();
        break;
      case R.id.tv_button:
        if (mNode != null && mNode.getIsPay() == 1) {
          ToastUtil.showMessage(mContext, "该车已付款, 无需再取证");
          return;
        }
        code = etCode.getText().toString();
        plateNumber = gpvPlateNumber.getPassWord();
        if (!StringUtils.isBlank(code) && !StringUtils.isBlank(plateNumber)) {
          mNode.setCode(code);
          mNode.setCarNumber(plateNumber);

          nbnode_record_unpay_code();
        } else {
          if (StringUtils.isBlank(code)) {
            ToastUtil.showMessage(mContext, "请输入车位号");
          }
          if (StringUtils.isBlank(plateNumber)) {
            ToastUtil.showMessage(mContext, "请输入车牌号");
          }
        }
        break;
    }
  }

  private void nbnode_record_unpay_code() {
    NbNodeRecordLogic.nbnode_record_unpay_code(mContext, code, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showNoCancelPd();
      }

      @Override public void onSucceed(Object obj) {
        APIM_NodeRecordInfo result = (APIM_NodeRecordInfo) obj;
        nodeRecord = result.getNodeRecordInfo();

        if (nodeRecord != null && !StringUtils.isBlank(nodeRecord.getStartTime())) {
          mNode.setStartTime(nodeRecord.getStartTime());
          printTicket();
        } else {
          CommonDialog.showYesDialog(mContext, "", "该车位未找到相应停车单", "确认", () -> {
          });
        }
      }

      @Override public void onFailed() {
        ToastUtil.showNetErrorMessage(mContext);
      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @Override protected void onDestroy() {
    super.onDestroy();
  }
}
